const db = require("@/db/index");

// 员工签到
// 查询考勤记录接口
exports.queryAttendance = (req, resp) => {
  try {
    const { pageSize = 10, pageNum = 1, staffNo, staffName, type } = req.body;
    // 构建查询条件
    let conditions = [];
    let params = [];

    if (staffNo) {
      conditions.push("staff_no LIKE ?");
      params.push(`%${staffNo}%`);
    }
    if (staffName) {
      conditions.push("staff_name LIKE ?");
      params.push(`%${staffName}%`);
    }
    if (type) {
      conditions.push("type LIKE ?");
      params.push(`%${type}%`);
    }

    // 组装WHERE子句
    const whereClause =
      conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "";

    // 查询总数
    const countSql = `SELECT COUNT(*) as total FROM employeeattendance ${whereClause}`;
    db.query(countSql, params, (err, totalResult) => {
      if (err) return resp.err(err);
      const total = totalResult[0].total;

      // 查询数据
      const offset = (pageNum - 1) * pageSize;
      const dataSql = `
    SELECT 
      id,
      create_time,
      staff_no,
      staff_name,
      position,
      department_name,
      type,
      time,
      remarks
    FROM employeeattendance
    ${whereClause}
    ORDER BY create_time DESC
    LIMIT ? OFFSET ?
  `;

      db.query(dataSql, [...params, pageSize, offset], (err, rows) => {
        if (err) return resp.err(err);

        resp.ok({
          total,
          list: rows,
          pageSize: Number(pageSize),
          pageNum: Number(pageNum),
        });
      });
    });
  } catch (error) {
    resp.err(error);
  }
};

// 修改考勤记录接口
exports.updateAttendance = async (req, resp) => {
  try {
    const { id, time, type, remarks } = req.body;
    console.log("req.body: ", req.body);

    // 验证必填字段
    if (!id) {
      return resp.err("记录ID不能为空");
    }

    // 构建更新字段
    const updateFields = [];
    const updateParams = [];

    if (time) {
      updateFields.push("time = ?");
      updateParams.push(new Date(time));
    }
    if (type) {
      updateFields.push("type = ?");
      updateParams.push(type);
    }
    if (remarks !== undefined) {
      updateFields.push("remarks = ?");
      updateParams.push(remarks);
    }

    // 如果没有可更新字段
    if (updateFields.length === 0) {
      return resp.err("没有需要更新的字段");
    }

    updateParams.push(id); // 添加ID作为WHERE条件参数

    // 先检查记录是否存在
    const checkSql = "SELECT * FROM employeeattendance WHERE id = ?";
    db.query(checkSql, [id], (checkErr, checkResults) => {
      if (checkErr) {
        console.error("检查记录失败:", checkErr);
        return resp.err("更新失败: " + checkErr.message);
      }

      if (checkResults.length === 0) {
        return resp.err("指定的考勤记录不存在");
      }

      // 执行更新
      const updateSql = `UPDATE employeeattendance SET ${updateFields.join(
        ", "
      )} WHERE id = ?`;
      db.query(updateSql, updateParams, (updateErr, updateResult) => {
        if (updateErr) {
          console.error("更新记录失败:", updateErr);
          return resp.err("更新失败: " + updateErr.message);
        }

        if (updateResult.affectedRows === 0) {
          return resp.err("未找到要更新的记录");
        }

        // 返回更新后的记录
        db.query(
          "SELECT * FROM employeeattendance WHERE id = ?",
          [id],
          (err, results) => {
            if (err) {
              console.error("获取更新后记录失败:", err);
              return resp.ok(null, "更新成功但未能获取最新数据");
            }
            resp.ok(results[0], "更新成功");
          }
        );
      });
    });
  } catch (error) {
    console.error("更新异常:", error);
    resp.err("更新失败: " + error.message);
  }
};

// 删除考勤记录接口
exports.deleteAttendance = async (req, resp) => {
  try {
    const ids = req.body;

    // 验证必填字段
    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return resp.err("签到记录ID列表不能为空");
    }

    // 删除签到记录数据
    const deleteSql = "DELETE FROM employeeattendance WHERE id IN (?)";
    db.query(deleteSql, [ids], (err, result) => {
      if (err) {
        console.error("删除签到记录失败:", err);
        return resp.err("删除签到记录失败: " + err.message);
      }
      if (result.affectedRows === 0) {
        return resp.err("未找到要删除的签到记录!");
      }
      resp.ok(
        {
          deletedCount: result.affectedRows,
        },
        `成功删除${result.affectedRows}个签到记录`
      );
    });
  } catch (error) {
    console.error("删除签到记录异常:", error);
    resp.err("删除签到记录失败: " + error.message);
  }
};

// 新增考勤记录接口
exports.addAttendance = (req, resp) => {
  try {
    const attendanceInfo = req.body;

    // 必填字段校验
    if (!attendanceInfo.staff_no) return resp.err("员工工号不能为空");
    if (!attendanceInfo.staff_name) return resp.err("员工姓名不能为空");
    if (!attendanceInfo.position) return resp.err("考勤类型不能为空");
    if (!attendanceInfo.department_name) return resp.err("考勤时间不能为空");

    // 构建插入数据（处理日期格式）
    const insertData = {
      staff_no: attendanceInfo.staff_no,
      staff_name: attendanceInfo.staff_name,
      position: attendanceInfo.position || null,
      department_name: attendanceInfo.department_name || null,
      time: attendanceInfo.time, // 转换日期格式
      type: attendanceInfo.type,
      remarks: attendanceInfo.remarks || null,
    };

    // 执行插入
    const insertSql = "INSERT INTO employeeattendance SET ?";
    db.query(insertSql, insertData, (err, result) => {
      if (err) {
        console.error("新增考勤记录失败:", err);
        return resp.err("新增失败: " + err.message);
      }
      if (result.affectedRows !== 1) return resp.err("新增失败");

      // 查询新增的完整记录
      db.query(
        `
        SELECT * FROM employeeattendance 
        WHERE id = ?`,
        [result.insertId],
        (err, rows) => {
          if (err) {
            console.error("获取新增记录失败:", err);
            return resp.ok(
              { id: result.insertId, ...insertData },
              "新增成功，但未能获取完整数据"
            );
          }
          resp.ok(rows[0], "新增成功");
        }
      );
    });
  } catch (error) {
    console.error("新增异常:", error);
    resp.err("新增失败: " + error.message);
  }
};
